package controllers

import (
	"encoding/json"
	"example.com/m/v2/global"
	"example.com/m/v2/model"
	"example.com/m/v2/model/common"
	"example.com/m/v2/model/request"
	"fmt"
	"github.com/brianvoe/gofakeit/v7"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"github.com/malisit/kolpa"
	"go.uber.org/zap"
	"net/http"
	"strconv"
	"strings"
	"syreclabs.com/go/faker"
	"time"
)

import _ "embed"

//go:embed data/emp.json

var empJSonStr string

//go:embed data/calendar.json
var calendarJsonStr string

type UserController struct {
}

func GetList() ([]model.UserModel, error) {
	users := make([]model.UserModel, 0, 10)

	users = append(users, model.UserModel{Username: "honghong", Gender: 2, Base: "北京", Id: 6})
	users = append(users, model.UserModel{Username: "qiangqiang", Gender: 2, Base: "北京", Id: 12})
	users = append(users, model.UserModel{Username: "zhangsonglin", Gender: 1, Base: "湖南", Id: 1})
	users = append(users, model.UserModel{Username: "liangliang", Gender: 2, Base: "北京", Id: 2})
	users = append(users, model.UserModel{Username: "c charp", Gender: 2, Base: "北京", Id: 11})
	users = append(users, model.UserModel{Username: "gogogo", Gender: 2, Base: "北京", Id: 6})
	users = append(users, model.UserModel{Username: "java", Gender: 2, Base: "北京", Id: 15})

	return users, nil
}

// Login
// @Summary 用戶登陸
// @Description 用戶名密碼登陸
// @Tags users
// @Accept json
// @Produce json
// @Param username header string true "用戶名"
// @Param password header string true "密碼"
// @Success 200 {string} string "ok"
// @Failure 400 {string} string "bad request"
// @Failure 500 {string} string "Internal Server Error"
// @Router /users/login [post]
func (c *UserController) Login(ctx *gin.Context) {
	username := ctx.GetHeader("username")
	password := ctx.GetHeader("password")

	user, err := apiService.userService.Login(username, password)

	if err != nil {
		zap.Error(err)
		ctx.JSON(http.StatusOK, gin.H{
			"code":     400,
			"msg":      "登陆失败! 用户名不存在或者密码错误!",
			"username": username,
			"password": password,
		})
	}

	//签发JWT
	claims := request.UserClaims{
		Uid: user.ID,
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS512, claims)
	tokenStr, err := token.SignedString([]byte(global.GVA_CONFIG.JWT.SigningKey))
	if err != nil {
		ctx.String(http.StatusInternalServerError, "系统错误")
		return
	}
	ctx.Header("x-jwt-token", tokenStr)
	//j := []byte(global.GVA_CONFIG.JWT.SigningKey) // 唯一签名
	//bf, _ := ParseDuration(global.GVA_CONFIG.JWT.BufferTime)
	//ep, _ := ParseDuration(global.GVA_CONFIG.JWT.ExpiresTime)
	//claims := j.CreateClaims(systemReq.BaseClaims{
	//	UUID:        user.GetUUID(),
	//	ID:          user.GetUserId(),
	//	NickName:    user.GetNickname(),
	//	Username:    user.GetUsername(),
	//	AuthorityId: user.GetAuthorityId(),
	//})

	ctx.JSON(http.StatusOK, gin.H{
		"code":     200,
		"msg":      "success",
		"username": username,
		"password": password,
	})
}

func (c *UserController) Register(w http.ResponseWriter, r *http.Request) {

}

func (c *UserController) Logout(w http.ResponseWriter, r *http.Request) {

}

// GetUserInfo
// @Summary 根据id获取用户信息
// @Description 根据id获取用户的详细信息
// @Tags users
// @Accept json
// @Produce json
// @Param id query int true "id"
// @Success 200 {string} string "ok"
// @Failure 400 {string} string "bad request"
// @Failure 500 {string} string "Internal Server Error"
// @Router /users/:id [get]
// @Security ApiKeyAuth
func (c *UserController) GetUserInfo(ctx *gin.Context) {
	k := kolpa.C("zh_CN")

	id, _ := strconv.Atoi(ctx.Query("id"))

	u := model.SysUser{
		Name:       k.Name(),
		ID:         id,
		Phone:      k.Phone(),
		Birthday:   k.DateTimeBetween(time.Date(1980, 1, 1, 0, 0, 0, 0, time.UTC), time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)),
		CreateTime: time.Now(),
		Account:    gofakeit.AchAccount(),
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code": 200,
		"data": u,
	})
}

// Update
// @Summary 修改用户信息
// @Description 修改用户信息
// @Tags users
// @Accept json
// @Produce json
// @Param UserModel body model.UserModel true "userinfo"
// @Success 200 {object} model.UserModel "ok"
// @Failure 400 {string} string "bad request"
// @Failure 500 {string} string "Internal Server Error"
// @Router /users [put]
// @Security ApiKeyAuth
func (c *UserController) Update(ctx *gin.Context) {
	claims, exists := ctx.Get("claims")
	if !exists {
		ctx.JSON(http.StatusUnauthorized, gin.H{
			"code": 401,
			"msg":  "用户信息错误",
		})
		return
	}

	userid, ok := claims.(*request.UserClaims)
	if !ok {
		ctx.String(http.StatusOK, "系统错误")
		return
	}

	user, err1 := apiService.userService.GetUserById(userid.Uid)
	if err1 != nil {
		ctx.JSON(http.StatusNotFound, gin.H{
			"code": "获取用户信息错误",
			"data": user,
		})
		return
	}

	err := ctx.ShouldBindJSON(&user)
	if err != nil {

	}

	ctx.JSON(http.StatusOK, gin.H{
		"code": 200,
		"data": user,
	})
}

// Delete
// @Summary 删除一个用户
// @Description 根据id删除用户
// @Tags users
// @Accept json
// @Produce json
// @Param id query int true "id"
// @Success 200 {string} string "ok"
// @Failure 400 {string} string "bad request"
// @Failure 500 {string} string "Internal Server Error"
// @Router /users [delete]
func (c *UserController) Delete(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Query("id"))

	ctx.JSON(http.StatusOK, gin.H{
		"code": 200,
		"data": id,
	})
}

// GetUserList
// @Summary 获取用户列表：获取全部用户列表。
// @Description 获取全部用户列表
// @Tags users
// @Accept json
// @Produce json
// @Param UserQueryModel query request.UserQueryModel true "用户列表查询参数"
// @Success 200 {string} string "ok"
// @Failure 400 {string} string "bad request"
// @Failure 500 {string} string "Internal Server Error"
// @Router /users [get]
// @Security ApiKeyAuth
func (c *UserController) GetUserList(ctx *gin.Context) {
	username := ctx.GetHeader("username")
	password := ctx.GetHeader("password")

	fmt.Println(username, password)

	var userQuery request.UserQueryModel
	err := ctx.ShouldBindQuery(&userQuery)
	if err != nil {

		ctx.JSON(200, gin.H{
			"data": nil,
			"code": 1,
			"msg":  err.Error(),
		})
		return
	}
	panic("我panic啦")
	time.Sleep(time.Second * 3)

	users, total, _ := apiService.userService.GetUserList(userQuery)

	//sort.Slice(users, func(i, j int) bool {
	//	return users[i].Id > users[j].Id
	//})

	ctx.JSON(200, gin.H{
		"data": common.PageResult{
			List:     users,
			Page:     userQuery.Page,
			PageSize: userQuery.PageSize,
			Total:    total,
		},
		"code": 0,
	})
}

// Create
// @Summary 添加一个用户
// @Description 添加一条用户数据
// @Tags users
// @Accept json
// @Produce json
// @Param UserModel body model.SysUser true "userinfo"
// @Success 200 {object} model.SysUser "ok"
// @Failure 400 {string} string "bad request"
// @Failure 500 {string} string "Internal Server Error"
// @Router /users [post]
func (c *UserController) Create(ctx *gin.Context) {
	var user model.SysUser
	_ = ctx.ShouldBind(&user)

	apiService.userService.Create(&user)

	ctx.JSON(http.StatusOK, gin.H{
		"code": 200,
		"data": user,
	})
}

// GetCalendarInfo
// @Summary 获取日程信息列表
// @Description 获取日程信息
// @Tags users
// @Accept json
// @Produce json
// @Router /users/GetCalendarInfo [get]
func (c *UserController) GetCalendarInfo(ctx *gin.Context) {
	//k := kolpa.C("zh_CN")

	var items []model.Calendar
	err := json.Unmarshal([]byte(calendarJsonStr), &items)
	if err != nil {
		fmt.Println(err)
	}

	var emps []model.Employee
	err = json.Unmarshal([]byte(empJSonStr), &emps)
	if err != nil {
		fmt.Println(err)
	}

	for i := 0; i < len(emps); i++ {
		emps[i].FullName = faker.Name().Name() //strings.Trim(k.Name(), " ")
	}

	for i := 0; i < len(items); i++ {
		//items[i].Start =
		s_temps := strings.Split(items[i].Start, "-")
		s_year := time.Now().Format("2006")
		s_month := time.Now().Format("01")
		s_day := s_temps[2]
		items[i].Start = s_year + "-" + s_month + "-" + s_day

		temps := strings.Split(items[i].End, "-")
		temps2 := strings.Split(temps[2], " ")
		e_temps := temps[0:2]
		e_temps = append(e_temps, temps2...)

		old_e_month, _ := strconv.Atoi(e_temps[1])
		old_s_month, _ := strconv.Atoi(s_temps[1])

		diff := old_e_month - old_s_month

		e_year := time.Now().Format("2006")
		e_month := time.Now().AddDate(0, diff, 0).Format("01")
		e_day := e_temps[2]
		e_time := e_temps[3]
		items[i].End = e_year + "-" + e_month + "-" + e_day + " " + e_time
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":  200,
		"emps":  emps,
		"items": items,
	})

	// 生成一个[0, 100)范围内的随机整数

	/**
	  {
	    "calendarId": 8397,
	    "resourceId": "678025",
	    "title": "India Holiday",
	    "start": "2025-03-14",
	    "end": "2025-03-14 23:59:59",
	    "backgroundColor": "#e6b8b7",
	    "borderColor": "#e6b8b7",
	    "textColor": "#fff"
	  }
	*/
}
